import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

// 路由配置表,清空
const routes = [
  {
    path: '/login',
    name: '/Login',
    component: () => import('../views/login/login.vue')
  },
  {
    path: '/',
    name: '/Layout',
    component: () => import('../views/layout/layout.vue'),
    // 二级路由
    children: [
      {
        path: '',
        name: 'home',
        component: () => import('../views/home/home.vue')
      },
      {
        path: 'articles',
        name: 'articles',
        component: () => import('../views/articles/articles.vue')
      },
      {
        path: 'image',
        name: 'image',
        component: () => import('../views/image/image.vue')
      },
      {
        path: 'addArticle',
        name: 'addArticle',
        component: () => import('../views/articles/add.vue')
      },
      {
        path: 'comment',
        name: 'Comment',
        component: () => import('../views/comment/comment.vue')
      },
      {
        path: 'fans',
        name: 'fans',
        component: () => import('../views/fans/fans.vue')
      },
      {
        path: 'settings',
        name: 'settings',
        component: () => import('../views/settings/settings.vue')
      }
    ]
  },
  // * 表示什么都能匹配,把它放在路由的最后,来匹配404页面
  {
    path: '*',
    name: 'page404',
    component: () => import('../views/page404/page404.vue')
  }
]

const router = new VueRouter({
  routes
})
// 路由守卫的格式
// 只要是发生了路由的跳转(还没有进入到目标路由),就会执行这个回调
// to:要跳入的路由信息,你要从哪里来
// from: 要跳出的路由信息,你从哪里来
// next: 是一个函数,放行方法
// - next() 正确跳转,允许进入到to路由
// -next(路由地址),不允许去to,而转去指定的路由地址
// 如果没有调用next(),则页面就不能正常显示了

// 如下页面是需要登录之后才能访问的
const authPageList = ['/', 'articles', '/images', 'xxxx']
router.beforeEach((to, from, next) => {
  console.log('发生了路由变化', from.path, '到', to.path)
  // 如果你要去的页面是主页，而你又没有登陆，则回到登陆页
  // if (to.path === '/' || to.path === '/articles') {
  if (authPageList.includes(to.path)) {
    if (localStorage.getItem('tokenStr')) {
      next()
    } else {
      console.log('你要去的是主页，但是你并没有登陆，所以路由导航守卫把你送到的Login')
      next('/login')
    }
  } else {
    if (to.path === '/login' && localStorage.getItem('tokenStr')) {
      // 如果你已经登陆了，就回去主页
      next('/')
    } else {
      next()
    }
  }
})
export default router
